<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <!-- 只要有表单都要表单进行验证，所以都要加上：mode和：rules -->
    <el-form ref="form" label-width="90px" :model="pass" :rules="rules">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pass.old_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pass.new_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input v-model="pass.re_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePwd">确认修改</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updatePwdAPI } from '@/api/user'
export default {
  name: 'UserInfo',
  data() {
    // 自定义规则：（1）新密码和确认密码要一致（2）原密码和新密码不能一样
    // value表示，谁使用这个验证规则，这个value值就是某个输入框的值
    // callback()表示验证通过
    // callback(new Error('xxx'))表示验证不通过，并提示错误
    const newPwd = (rule, value, callback) => {
      if (value === this.pass.old_pwd) {
        callback(new Error('新密码和原密码不能一样'))
      } else {
        callback()
      }
    }
    // 新密码和确认密码要一致
    const rePwd = (rule, value, callback) => {
      if (value !== this.pass.new_pwd) {
        callback(new Error('两个密码不一致'))
      } else {
        callback()
      }
    }
    return {
      pass: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      // 对上面的属性的验证
      rules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: newPwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: rePwd, trigger: 'blur' }
        ]
      }
    }
  },
  // 点击确认修改后，就发送ajax请求，修改密码
  methods: {
    async updatePwd() {
      const { data: res } = await updatePwdAPI(this.pass)
      if (res.code === 1) {
        // 提示修改成功的信息
        this.$message.success(res.message)
        // 修改成功后，清除token和user
        this.$store.commit('user/updateToken', '')
        this.$store.commit('user/updateUser', '')
        // 退出到登录页面
        this.$router.push('/login')
      } else {
        // 提示修改失败的信息
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style scoped lang="less">
.el-form {
  width: 500px;
}
.el-form {
  width: 500px;
}
.el-form-item /deep/ .el-form-item__label {
  font-size: 13px;
}
.el-card {
  font-size: 13px;
}
.el-button {
  font-size: 13px;
}
.el-input {
  font-size: 13px;
}
</style>
